package cn.gogpay.dcb.api.mq;

import cn.gogpay.dcb.api.common.constant.BizConstant;
import cn.gogpay.dcb.api.entity.OrderRecord;
import cn.gogpay.dcb.api.service.RechargeRecordService;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.UUID;

/**
 * @author zhanglong@gogpay.cn
 * @date 2019/12/4 18:58
 */
@Component
@RabbitListener(queues = BizConstant.BUS_ORDER_WRITER_OFF)
public class ExceptionWriteoffOrderPaidReceiver {
    private Logger logger = LoggerFactory.getLogger(this.getClass().getName());
    @Autowired
    private RechargeRecordService rechargeRecordService;

    @RabbitHandler
    public void process(String message) throws Exception {
        try {
            logger.info("接收未销帐订单队列信息:message={}", message);
            OrderDTO orderDTO = JSONObject.parseObject(message,OrderDTO.class);
            String payStatus = orderDTO.getPayStatus();
            String orderNo = orderDTO.getOrderNo();
            String payType = orderDTO.getPayType();
            OrderRecord record = rechargeRecordService.findByOrderNo(orderNo);
            if (null==record){
                String cardNo=orderDTO.getConsNo();
                try {
                    OrderRecord orderRecord = rechargeRecordService.findByCardNo(cardNo);
//                    record.setId(UUID.randomUUID().toString().replaceAll("-",""));
                    record = new OrderRecord();
                    record.setBalance("0");
                    record.setPrice(orderDTO.getAmt());
                    record.setUserId(orderDTO.getUserId());
                    record.setCardNo(cardNo);
                    record.setUpdateTime(orderDTO.getPayTime());
                    record.setStatus("0");
                    record.setOrderNo(orderNo);
                    record.setPhone(orderRecord.getPhone());
                    record=rechargeRecordService.save(record);
                }catch (Exception ex){
                    logger.info("处理异常订单出错",ex);
                    return;
                }
            }
            record.setPayType(payType);
            record.setPayStatus(payStatus);
            if ("01".equals(payStatus)) {
                record.setStatus("1");
            }
            rechargeRecordService.updateOrder(record);
        }catch (Exception ex){
            logger.warn("处理订单支付状态改变队列信息出错",ex);
        }
    }

}
